package config;

import javax.servlet.Filter;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

/**
 * Implement the Interface {@link WebApplicationInitializer} in order to 
 * configure the ServletContext programmatically as opposed to the web.xml
 * 
 * @author liujinliang
 *
 */
public class MyWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

	@Override
	protected Class<?>[] getRootConfigClasses() {
		return null;
	}

	/**
	 * DispatcherServlet 配置，配置Conntroller相关的Bean：
	 * ViewResolver etctera.
	 */
	@Override
	protected Class<?>[] getServletConfigClasses() {
		
		/** Deal with the SpringMVC Configuration, like viewReslover */
		return new Class[] { WebConfig.class };
	}

	/**
	 * 配置DispatcherServlet 拦截的请求，此处为拦截所有请求
	 */
	@Override
	protected String[] getServletMappings() {
		
		/** Setting the RequestMapping for DispatcherServlet */
		return new String[] { "/" };
	}
	
	/**
	 * 如果我们只想为这个DispatcherServlet配置filter的话，直接实现getServletFilters()就 OK
	 * 但是如果想要配置额外的 servlet 以及 filters 我们就需要实现 WebApplicationInitializer 接口
	 * public class MyServletInitializer implements WebApplicationInitializer {
	 *     @Override
	 *     public void onStartup(ServletContext throws ServletException {
	 *         Dynamic myServlet = servletContext.addServlet("myServlet", MyServlet.class);
	 *         myServlet.addMapping("/custom/**");
	 *         
	 *         // 定义filter
	 *         javax.servlet.FilterRegistration.Dynamic filter = 
	 *             servletContext.addFilter("myFilter", MyFilter.class);
	 *         filter.addMappingForUrlPatterns(null, false, "/custom/*");
	 *     }
	 * }
	 */
	@Override
	protected Filter[] getServletFilters() {
		return new Filter[] { new GlobalFilter() };
	}
	
	
}
